import THREE from './three.js';

function Card(w, h, aTexture, bTexture, cTexture = null){
    var plane = new THREE.Mesh( new THREE.PlaneBufferGeometry( w, h ), new THREE.MeshLambertMaterial( { 
        map: aTexture,
        side: THREE.DoubleSide } ) );
    plane.castShadow = true;
    plane.material.onBeforeCompile = function (shader) {
        var fragmentShader = shader.fragmentShader;
        fragmentShader = fragmentShader.replace('#include <map_pars_fragment>', `
        #ifdef USE_MAP

            uniform sampler2D map;
            uniform sampler2D map2;
            ${(cTexture)?'uniform sampler2D textmap;':''}
        #endif`);
        fragmentShader = fragmentShader.replace('#include <map_fragment>', `
        #ifdef USE_MAP

            vec4 texelColor;
            if(!gl_FrontFacing){
                texelColor = texture2D( map2, vec2(1.0-vUv.x, vUv.y) );
            }
            else{
                float edgex = 0.1/2.0;
                float edgey = 0.1/2.0;
                if(vUv.x<edgex || 1.0-edgex<vUv.x || vUv.y<edgey || 1.0-edgey<vUv.y){
                    texelColor = vec4(1.0, 1.0, 1.0, 1.0);
                }
                else if(vUv.x<(edgex+0.005) || 1.0-(edgex+0.005)<vUv.x || vUv.y<(edgey+0.005) || 1.0-(edgey+0.005)<vUv.y){
                    texelColor = texture2D( map, vec2((vUv.x-edgex)/(1.0-2.0*edgex), (vUv.y-edgey)/(1.0-2.0*edgey)) )*0.5+vec4(1.0, 1.0, 1.0, 1.0)*0.5;
                }
                else{
                    texelColor = texture2D( map, vec2((vUv.x-edgex)/(1.0-2.0*edgex), (vUv.y-edgey)/(1.0-2.0*edgey)) );
                }
                ${(cTexture)?`
                vec4 textColor = texture2D(textmap, vUv);
                texelColor = vec4(textColor.xyz*textColor.w+texelColor.xyz*(1.0-textColor.w), 1.0);
                `:''}
            }

            texelColor = mapTexelToLinear( texelColor );
            diffuseColor *= texelColor;

        #endif`);
        shader.fragmentShader = fragmentShader;
        shader.uniforms.map2 = { value: bTexture };
        if(cTexture){
            shader.uniforms.textmap = { value: cTexture };
        }
        plane.material.shader = shader;
    }
    return plane;
}

export default Card;